<?php

namespace Caifenglei\AuthRbac\Http\Controllers;

use Caifenglei\AuthRbac\Http\Actions\UserAction;
use Caifenglei\AuthRbac\Http\Requests\UpdateUserRequest;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Spatie\Permission\Exceptions\RoleDoesNotExist;

class UserController extends Controller
{
    public function index(Request $request): JsonResponse
    {
        $keyword  = $request->input('keyword', '');
        $type   = $request->input('type', '');
        $pageSize = $request->input('page_size', 15);

        $query = UserAction::getUserClass()::with(['roles' => function($query){
            $query->orderBy('sort');
        }])->orderBy('updated_at', 'desc');
        if($keyword){
            $query->where('name', 'like', "%{$keyword}%")
                ->orWhere('username', 'like', "%{$keyword}%");
        }
        if($type) {
            $query->where('identifiable_type', $type);
        }

        $users = $query->paginate($pageSize);
        return $this->success('用户列表', $this->formatPaginate($users));
    }

    /**
     * 获取单个用户信息
     * @param Request $request
     * @param $id
     * @return JsonResponse
     */
    public function show(Request $request, $id): JsonResponse
    {
        //TODO 字段过滤pivot等
        $user = UserAction::getUserClass()::with(['roles' => function($query){
            $query->orderBy('sort');
        }])->find($id);
        if($user){
            return $this->success('获取用户信息成功', ['user' => $user->toArray()]);
        }else{
            return $this->fail('用户不存在');
        }
    }

    /**
     * 更新用户信息及角色
     * @param UpdateUserRequest $request
     * @param $id
     * @return JsonResponse
     */
    public function update(UpdateUserRequest $request, $id): JsonResponse
    {
        $validated = $request->validated();
        $user = UserAction::getUserClass()::find($id);
        if (!$user) {
            return $this->fail('更新失败，用户不存在');
        }
        try {
            UserAction::assignRoles($user, $validated);
        }catch (RoleDoesNotExist $e){
            return $this->fail('分配给用户的角色不存在');
        }
        return $this->success('用户更新成功');
    }
}
